/**
 * Copyright (c) 2017 hadlinks, All Rights Reserved.
 */
package com.bugull.farm.core.proxy;

import com.bugull.farm.core.proxy.example.AfterHandlerImpl;
import com.bugull.farm.core.proxy.example.BeforeHandlerImpl;
import com.bugull.farm.core.proxy.example.Calculator;
import com.bugull.farm.core.proxy.example.CalculatorImpl;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Project Name: bugu-farm-household 
 * Package Name: com.bugull.farm.core.proxy 
 * ClassName: ProxyFactory 
 * Function: TODO ADD FUNCTION.  
 * date: 2017/11/7 16:45
 * @author songwei (songw@hadlinks.com)
 * @since JDK 1.8 
 */
public class ProxyFactory {

    /**
     * 获取代理对象，代理目标targetObject
     * @param targetObject
     * @param handlers
     * @return
     */
    public static Object getProxy(Object targetObject, List<AbstractHandler> handlers) {
        Object proxyObject = null;
        if (handlers.size() > 0) {
            proxyObject = targetObject;
            for (int i = 0; i < handlers.size(); i++) {
                handlers.get(i).setTargetObject(proxyObject);
                proxyObject = Proxy.newProxyInstance(targetObject.getClass()
                        .getClassLoader(), targetObject.getClass().getInterfaces(), handlers.get(i));
            }
            return proxyObject;
        } else {
            return targetObject;
        }
    }

    public static void main(String[] args) {
        CalculatorImpl cal = new CalculatorImpl();
        BeforeHandler before = new BeforeHandlerImpl();
        AfterHandler after = new AfterHandlerImpl();
        List<AbstractHandler> handlers = new ArrayList<AbstractHandler>();
        handlers.add(before);
        handlers.add(after);
        Calculator proxy = (Calculator)ProxyFactory.getProxy(cal, handlers);
        System.out.println(proxy.calculate(1, 2));
    }
}
